﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace CommonClass
{
    /// <summary>
    /// 序列化操作
    /// </summary>
    public class XMLSerializer
    {
        #region XML 序列化与反序列化操作

        /// <summary>
        /// XML 序列化
        /// <para>该方法可以解析很多类型，包括：抽象类，数组，子类型等</para>
        /// </summary>
        /// <param name="FormatObject"></param>
        /// <returns></returns>
        public static string SerializeXML(object FormatObject)
        {
            Type T = FormatObject.GetType();
            // XML 序列化开始
            MemoryStream ms = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(T);
            xml.Serialize(ms, FormatObject); // XML 序列化的关键代码 
            byte[] arr = ms.ToArray();
            ms.Close();
            string xmlString = Encoding.UTF8.GetString(arr, 0, arr.Length);
            ms.Close();

            return xmlString;
        }

        /// <summary>
        /// XML 反序列化
        /// </summary>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static Object DeserializeXML<T>(string xmlString)
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
            XmlSerializer xml = new XmlSerializer(typeof(T));
            T obj = (T)xml.Deserialize(ms); // XML 反序列化的关键代码
            ms.Close();

            return obj;
        }

        #endregion
    }
}
